<!--
*@Author: QWP
*@Description: 收文管理
*@Params: pType  1/收文登记     2/收文登记审核     3/发文归档     4/接收的收文查询
*@Date: 2024-07-08 09:51:28
-->
<template>
  <a-layout class="f-h-100 s-bg-white" id="test">
    <u-table-header>
      <u-form
        :model="searchF.model"
        :gutter="16"
        :elements="searchEl"
        class="f-w-auto"
        :isSearch="true"
        @formChange="getSearch(1)">
        <a-col>
          <u-button-space>
            <u-icon-button @click="getSearch(1)">查询</u-icon-button>
            <template v-if="pType != 4">
              <u-icon-button itype="record" @click="showFlow = true"
                v-if="isReport != true">
                流程记录
              </u-icon-button>
              <u-icon-button itype="transmit" @click="toSendDoc" v-if="pType == 1">
                收文推送
              </u-icon-button>
            </template>
          </u-button-space>
        </a-col>
        <a-col flex="1">
          <a-row justify="end">
            <a-space>
              <template v-if="pType == '1'">
                <u-icon-button itype="add" @click="toEdit(1)">新增</u-icon-button>
                <u-icon-button itype="edit" @click="toEdit(2)">修改</u-icon-button>
                <u-icon-button itype="report" @click="auditAbout('1')">上报</u-icon-button>
                <u-icon-button itype="recall" @click="auditAbout('4')">取回</u-icon-button>
                <u-icon-button itype="delete" @click="deleteBtn">删除</u-icon-button>
                <!-- <u-icon-button itype="import" @click="showImp = true">批量导入</u-icon-button> -->
              </template>
              <template v-else-if="pType == '2'">
                <u-icon-button itype="audit" @click="auditAbout('2')"
                  v-if="showAuditBnt">审核</u-icon-button>
                <u-icon-button itype="recall" @click="auditAbout('4')"
                  v-if="searchF.model.adstatus == '1'">取回</u-icon-button>
                <u-icon-button itype="close" @click="auditAbout('3')"
                  v-if="showAuditBnt">退回</u-icon-button>
              </template>
              <template v-if="pType == '3'">
                <u-icon-button itype="sort" @click="collectSort">归档</u-icon-button>
                <!-- <u-icon-button itype="export" @click="">导出</u-icon-button> -->
                <!-- <u-icon-button itype="print" @click="">批量打印</u-icon-button> -->
              </template>
            </a-space>
          </a-row>
        </a-col>
      </u-form>
    </u-table-header>
    <u-table-content>
      <u-table
        :columns="columns"
        :data="tabData"
        :loading="loading"
        v-model:pagination="pagenation"
        :scroll="{y: useTableScroll() }"
        @onDblclick="(record) => {
          current = record;
          showEdit = true;
        }"
        @onSelect="({selectedRows}) => tabSelData = selectedRows"></u-table>
    </u-table-content>
  </a-layout>

  <!-- 编辑弹窗 -->
  <Edit v-model:open="showEdit"
    wrap-class-name="full-modal"
    :title="dialogTitle" 
    :current="current"
    :isAudited="showAuditBnt"
    @success="showEdit = false; current = {}; getSearch()"
    @close="current = {}"/>
  
  <!-- 导入 -->
  <u-imp-data v-model:open="showImp"></u-imp-data>

  <!-- 流程记录 -->
  <u-act-flowd v-model:open="showFlow"
    :selDatas="tabSelData"
    busiType="income_doc"/>
  
  <!-- 收文推送 -->
  <SendDoc v-model:open="showSend"
    title="收文转发"
    width="600px"
    :current="sendRow"
    @close="sendRow = {}"
    @success="showSend = false; sendRow = {}, getSearch()"/>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, h, watch, onActivated, toRefs, toRaw } from "vue";
import { useRoute, useRouter, onBeforeRouteUpdate, onBeforeRouteLeave} from "vue-router";
import { _IFormEl } from "@/components/common/form/interface";
import { ColProps, FormItemProps, TableColumnProps } from "ant-design-vue";
import { CheckCircleOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue';
import UIconFont from '@/components/common/iconfont/IconFont.vue'
import { jsonCopy, nullC, alertC, messageC } from '@/util/common'
import { useBaseStore } from '@/store'
import { storeToRefs } from 'pinia'
import dayjs from "dayjs";
import { cloneDeep } from 'lodash'
import { useAuditAbout, IAuditParams } from '@/hooks/useAudit'
import { useSearchShow } from "@/hooks/useAuditEl";
import { formatEmergency } from '@/views/oa/officialDoc/dispatch/emergencyTool.ts'
import { useTableScroll } from "@/hooks/useTable";
import { statusA } from "@/common/model/base";
import Edit from './Edit.vue'
import SendDoc from './SendMsg.vue'
import * as dispatchApi from '@/service/officialDoc/publishDoc/index.ts'

const props = defineProps<{
  current?: object,
  isReport?: boolean
}>()

const route = useRoute();
const { pType } = route.params
const router = useRouter();

const { fileNoChars } = storeToRefs(useBaseStore())

let test = ref({a: 666})
onMounted(() => {
  initParams()
})

let pagenation = reactive({
  total: 0,
  current: 1,
  pageSize: 50,
})
const searchF = reactive({
  model: {
    acceptDate: '',
    keywords: '',
    docType: 2
  },
});

// 曾经办，不显示审核和退回按钮
const showAuditBnt = ref<boolean>(
  useSearchShow(searchF.model, '1', { key: 'adstatus', result: false, noResult: true })
)

const formItemProps: FormItemProps = {
  labelWidth: '72px',
  style: {
    width: '220px'
  }
};
const searchEl: Array<_IFormEl> = [
  { label: "审核状态", key: "status", element: "select",
    formItemProps: formItemProps,
    hide: pType != '1',
    componentProps: {
      options: statusA()
    }
  },
  { label: "审核状态", key: "adstatus", element: "select",
    formItemProps: formItemProps,
    hide: pType != '2',
    componentProps: {
      allowClear: false,
      options: [
        {label: '待审核', value: '0'},
        {label: '曾经办', value: '1'},
      ]
    }
  },
  { label: "收文日期", key: "acceptDate", element: "datepicker", formItemProps: formItemProps },
  { label: "关键字", key: "keywords", element: "input",
    formItemProps: { ...formItemProps, labelWidth: '50px'},
    componentProps: {
      placeholder: "内容摘要",
    },
  },
];

// 列表
const loading = ref<boolean>(false)
const tabSelData = ref([]);
const tabData = ref([]);
let originCols: Array<TableColumnProps> = reactive([
  { dataIndex: "incdocunitname", title: "来文单位", width: 200 },
  { dataIndex: "incName", title: "收文编号", width: 150, align: 'center', 
    customRender: ({ text, record }) => {
      const { fileNoChar, fileNoYear, fileNoOrder } = record;
      let noInfo = fileNoChars.value.find(i => i.value == fileNoChar) || {}
      return text ? `${nullC(noInfo['label'])}[${nullC(fileNoYear)}]${nullC(fileNoOrder)}` : ''
    }
  },
  { dataIndex: "urgencyDegree", title: "紧急程度", width: 120, align: 'center',
    customRender: ({ text }) => formatEmergency(text)
  },
  { dataIndex: "docabs", title: "内容摘要", width: 200, },
  { dataIndex: "isSecretRelated", title: "是否涉密", width: 120, align: 'center',
    customRender: ({ text }) => text == '1' ? '是' : '否' 
  },
  { dataIndex: "acceptDate", title: "收文时间", width: 150, align: 'center', 
    customRender: ({ text }) => (text || '').split(' ')[0]
  },
  { dataIndex: "tousername", title: "通知人员", width: 150, align: 'center', },
  ...(props.isReport == true ? [] : [
    { dataIndex: "taskname", title: "公文环节", width: 150,}
  ]),
]);
let columns: Array<TableColumnProps> = reactive([])

// 列表查询
const getSearch = async (currnt?: number) => {
  if(currnt == 1) {
    pagenation.current = currnt
  }
  loading.value = true;
  try {
    searchF.current = pagenation.current
    searchF.size = pagenation.pageSize
    const res = await dispatchApi.page(searchF)
    if(res.code == 0) {
      tabData.value = res.data.records || [];
      pagenation.totla = res.total || [];
    }
  } catch (error) {}
  loading.value = false;
}

// onBeforeRouteUpdate((to, from, next) => {
//   initParams(to)
//   next();
// })

onActivated(() => {
  initParams(route)
})

// 初始化页面参数
const initParams = (to?) => {
  let tTo = to ? to : route
  
  let tCols = cloneDeep(originCols)
  // 发文拟稿，签批、归档要审核状态
  if(['1', '2',].includes((to ? to : route).params.pType)) {
    tCols.push({ dataIndex: "reauditusername", title: "当前审核人", width: 150, align: 'center',},)
  }
  // 归档 
  if(['3'].includes((to ? to : route).params.pType)) {
    tCols.push({ dataIndex: "isFilter", title: "是否归档", width: 100, align: 'center',
      customRender: ({ text }) => text == '1' ? '是' : '否'
    })
  }
  // 收到的文章查询 
  if(['4'].includes((to ? to : route).params.pType)) {
  }
  columns.splice(0, columns.length, ...tCols)

  const isAudit = {
    1: '0', 2: '1', 3: '2', 4: '2'
  }
  searchF.model.isAudit = isAudit[tTo.params.pType]
  searchF.model.adstatus = searchF.model.isAudit == 1 ? '0' : ''
  searchF.model.status = pType == 1 ? '1' : ''

  // 报表 页面直接查询审核完成的数据
  if(props.isReport == true) {
    searchF.model.status = '3'
  }

  getSearch()
}

// 编辑
const current = ref<object>({})
let dialogTitle = ref<string>("收文登记")
let showFlow = ref<boolean>(false)
let showEdit = ref<boolean>(false)
const toEdit = (type: number) => {
  if(type == 2) {
    if(tabSelData.value.length != 1) {
      messageC("请先选择一条数据进行编辑!");
      return
    }
    current.value = tabSelData.value[0]
  }
  showEdit.value = true
}

// 删除
const deleteBtn = () => {
  if (tabSelData.value.length == 0) {
    messageC("请先选择要删除的数据!", "warning");
    return;
  }

  let noDel = tabSelData.value.some(i => ['2', '3'].includes(i['status'] + ''))
  if(noDel) {
    messageC("审核中或审核完成的数据不能删除!");
    return
  }

  let ids = tabSelData.value.map((item) => item.keyid);
  alertC("确定删除选中的数据?", 'confirm').then(async () => {
    try {
      loading.value = true;
      const data = await dispatchApi.del({ longs: ids.join(",") });
      if (data.code == 0) {
        messageC(data.msg, "success");
        getSearch();
      } else {
        alertC(data.msg, "warning");
      }
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  })
}

// 上报、审核、退回
const auditAbout = async (type: string) => {
  loading.value = true;
  const auditParams: IAuditParams = {
    type: 'income_doc',
    selDatas: tabSelData.value
  }
  try {
    const res = await useAuditAbout(type, auditParams)
    if(res) {
      pagenation.current = 1;
      getSearch()
    }
  } catch (error) {}
  loading.value = false;
}

// 归档
const collectSort = async() => {
  if(tabSelData.value.length != 1) {
    messageC("只能选择一条数据进行归档!");
    return
  }

  if(tabSelData.value[0]['isFilter'] == 1) {
    messageC("请选择未归档的数据进行操作!");
    return
  }
  await alertC("确认归档?", "confirm")
  loading.value = true;
  try {
    const res = await dispatchApi.updateIsFilter(tabSelData.value[0]['keyid'])
    if(res.code == 0) {
      messageC(res.msg, "success");
      getSearch();
    }
    else {
      messageC(res.msg, "error");
    }
  } catch (error) {}
  loading.value = false
}

// 收文推送
const showSend = ref<boolean>(false)
const sendRow = ref({})
const toSendDoc = () => {
  if(tabSelData.value.length != 1) {
    messageC("请选择一条数据进行推送！");
    return
  }

  if(tabSelData.value[0]['status'] != 3) {
    messageC("只能选择审核完成的数据进行推送！");
    return
  }

  sendRow.value = tabSelData.value[0]
  showSend.value = true
}

// 导入
let showImp = ref<boolean>(false)

defineExpose({
  toEdit
})
</script>

<style lang="scss" scoped>
.icons-list :deep(.anticon) {
  margin-right: 6px;
  font-size: 24px;
}
</style>
